/**
 * @file xgame_2048.c
 *
 */

#include "xgame_2048.h"
#include "xgame_ary.h"
#include "xgame_matrix.h"
#include <string.h>

/*********************
 *      DEFINES
 *********************/

/**********************
 *      TYPEDEFS
 **********************/

/**********************
 *  STATIC PROTOTYPES
 **********************/

static void vol0_full_random(struct _xgame_2048  *game);
static int8_t is_failed(struct _xgame_2048  *game);

static void key_left(struct _xgame_2048  *game);
static void key_right(struct _xgame_2048  *game);
static void key_up(struct _xgame_2048  *game);
static void key_down(struct _xgame_2048  *game);

 /**********************
 *  STATIC VARIABLES
 **********************/

/**********************
 *      MACROS
 **********************/

/**********************
 *   GLOBAL FUNCTIONS
 **********************/

void xgame_2048_init(struct _xgame_2048 *game, const struct _xgame_2048cfg *cfg,
                     uint16_t *matrix, uint16_t *row_buf)
{
  game->cfg = cfg;
  game->matrix = matrix;
  game->row_buf = row_buf;
  game->random_vol = 2;
  /*matrix init*/
  memset(game->matrix, 0, cfg->col_count * cfg->row_count * sizeof(uint16_t));
  vol0_full_random(game);
  vol0_full_random(game);
}

int8_t xgame_2048_key_pro(struct _xgame_2048  *game, uint8_t key)
{
    if(key == 0) key_left(game);
    //else if(key == 1) key_right(game);
    //else if(key == 2) key_top(game);
    //else if(key == 3) key_down(game);
    else return 0;

    uint16_t col_count = game->cfg->col_count;
    uint16_t row_count = game->cfg->row_count;
    if((ary_get_max(game->matrix, col_count * row_count)) >= game->cfg->win_max)
      return 1;
    if((ary_get_min(game->matrix, col_count * row_count)) == 0){
      vol0_full_random(game);
      return 0;
    }
    /*determine whether it has failed*/
    return is_failed(game);
}

/**********************
 *   STATIC FUNCTIONS
 **********************/
static void vol0_full_random(struct _xgame_2048  *game)
{


}

/*return0: contiue, -1: fail*/
static int8_t is_failed(struct _xgame_2048  *game)
{
  return 0;
}

static void key_left(struct _xgame_2048  *game)
 {
    uint16_t col_count = game->cfg->col_count;
    uint16_t row_count = game->cfg->row_count;
    uint16_t *rol = game->matrix;
    uint16_t *rol_end = rol + col_count * row_count;
    for(; rol < rol_end; rol += row_count){
        uint16_t *end = ary_merge_to_left(rol, row_count);
        end = ary_combine_to_left(rol, end - rol);
        memset(end, 0, (row_count - (end - rol)) * sizeof(uint16_t));
    }
 }
